const util = require("../../utils/utils.js")
const watch = require("../../utils/watch.js")
const app = getApp()
// pages/forum-edit/edit.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    collapseActiveNames: ["1"],
    fileList: [
      // {
      //   url: 'https://img.yzcdn.cn/vant/leaf.jpg',
      //   name: '图片1',
      // },
      // // Uploader 根据文件后缀来判断是否为图片文件
      // // 如果图片 URL 中不包含类型信息，可以添加 isImage 标记来声明
      // {
      //   url: 'http://iph.href.lu/60x60?text=default',
      //   name: '图片2',
      //   isImage: true,
      //   deletable: true,
      // },
    ],
    photoUrl: "",
    upCount: 0,
    option1: [{
        text: '出售',
        value: 0
      },
      {
        text: '求购',
        value: 1
      },
      {
        text: '交换',
        value: 2
      },
    ],
    value1: 0,
    option2: [{
        text: '生活',
        value: "生活"
      },
      {
        text: '学习',
        value: "学习"
      },
      {
        text: '穿搭',
        value: "穿搭"
      },
      {
        text: '其他',
        value: "其他"
      },
    ],
    value2: "生活",
    isExchange: 0,
    content: null,
    type: 0,
    price: null,
    exchange: null,
    category: "生活",
    status: null,
    itemname: null,
    isEdit: false
  },
  onCollapseChange: function (event) {
    this.setData({
      collapseActiveNames: event.detail,
    });
  },

  

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      isEdit: app.globalData.dealIsEdit
    })
    app.globalData.dealIsEdit = false
    if (this.data.isEdit) {
      wx.setNavigationBarTitle({
        title: "编辑商品"
      });
      var that = this
      wx.request({
        url: 'http://localhost:8888/dealing/getDealingById',
        method: 'GET',
        data: {
          id: app.globalData.editDealingId
        },
        header: {
            'content-type': 'application/json'
        },
        success: function (res) {
          var photo = util.strToArr(res.data.data.photo)
          console.log(photo);
          var photoList = []
          for(var i=0;i<photo.length;i++) {
            var o = {url: photo[i], name: "图片"+i}
            photoList.push(o)
          }
          console.log(photoList);
          that.setData({
            content: res.data.data.content,
            fileList: photoList,
            type: res.data.data.type,
            category: res.data.data.category,
            itemname: res.data.data.itemname,
            price: res.data.data.price,
            status: res.data.data.status
          })
        }
    })
    } else {
      wx.setNavigationBarTitle({
        title: "发布商品"
      });
    }
    watch.setWatcher(this)
  },

  watch: {
    'upCount': function (value, oldValue) {
      this.insertDealing(value)
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  onDeletePicItem: function (e) {
    let index = e.detail.index;
    let fileList = this.data.fileList;
    fileList.splice(index, 1);
    this.setData({
      fileList
    });
    console.log(e.detail);
  },

  afterRead: function (event) {
    console.log(event.detail);
    let fileList = this.data.fileList;
    // 填充新图片的对象元素
    let obj = {};
    obj.url = event.detail.file.url;
    obj.name = "图片" + (fileList.length + 1);
    obj.deletable = true;
    // console.log(fileList.pop());
    fileList.push(obj);
    this.setData({
      fileList
    });
    console.log(this.data.fileList);

  },
  onChange({
    detail
  }) {
    this.setData({
      isExchange: detail
    })
  },
  onSubmit(e) {
    var content = e.detail.value.content
    //console.log(content);
    var type = e.detail.value.type
    //console.log(type);
    var category = e.detail.value.category
    //console.log(category);
    var title = e.detail.value.title
    //console.log(title);
    var price = e.detail.value.price
    if (price == null) {
      price = 0
    }
    //console.log(price);
    var exchange = e.detail.value.exchange
    if (exchange == null) {
      exchange = ""
    }
    //console.log(exchange);
    var count = e.detail.value.count
    //console.log(count);
    var that = this
    this.setData({
      content: content,
      type: type,
      price: price,
      exchange: exchange,
      category: category,
      status: count,
      itemname: title,
    })
    if (!util.validMoney(price)) {
      wx.showToast({
        icon: 'error',
        title: '价格错误',
      })
    } else {
      wx.showLoading({
        title: '上传中',
        mask: true
      })
      if(this.data.fileList.length == 0) {
        that.setData({
          upCount: 0
        })
      }
      for (let i = 0; i < this.data.fileList.length; i++) {
        if(this.data.fileList[i].url.indexOf("http://tmp/") != -1) {
        this.uploadImg({
          url: "http://localhost:8888/image/upload",
          path: that.data.fileList[i].url
        })
      }
      else {
        var photo = this.data.photoUrl
        var url = this.data.fileList[i].url
        var count = this.data.upCount
        if(photo == "") {
          that.setData({
            photoUrl: url,
            upCount: count + 1
          })
        }
        else {
          that.setData({
            photoUrl: photo + "`" + url,
            upCount: count + 1
          })
        }
      }
      }
    }
  },
  uploadImg: function (data) {
    var that = this
    wx.uploadFile({
      filePath: data.path,
      name: 'file',
      url: data.url,
      success: (res) => {
        let url = JSON.parse(res.data).data;
        let photo = that.data.photoUrl
        let count = that.data.upCount
        if (photo == "") {
          that.setData({
            photoUrl: photo + url,
            upCount: count + 1
          })
        } else {
          that.setData({
            photoUrl: photo + "`" + url,
            upCount: count + 1
          })
        }
        //console.log(this.data.photoUrl);
      },
      fail: (res) => {
        console.log(res);
      },
    })
  },
  insertDealing(count) {
    if (count == this.data.fileList.length) {
      wx.hideLoading({
        success: (res) => {},
      })
      console.log(this.data.photoUrl);
      var username = app.globalData.loginAccount
      var content = this.data.content
      var photo = this.data.photoUrl
      var type = this.data.type
      var price = this.data.price
      var exchange = this.data.exchange
      var category = this.data.category
      var status = this.data.status
      var itemname = this.data.itemname
      if (!this.data.isEdit) {
        wx.request({
          url: 'http://localhost:8888/dealing/insertDealing',
          method: 'POST',
          data: {
            username: username,
            content: content,
            photo: photo,
            type: type,
            price: price,
            exchange: exchange,
            category: category,
            status: status,
            itemname: itemname
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: res => {
            wx.switchTab({
              url: '../secondhand-home/home',
            })
            wx.showToast({
              title: '发布成功',
            })
          }
        })
      } else {
        wx.request({
          url: 'http://localhost:8888/dealing/editDealing',
          method: 'POST',
          data: {
            id: app.globalData.editDealingId,
            username: username,
            content: content,
            photo: photo,
            type: type,
            price: price,
            exchange: exchange,
            category: category,
            status: status,
            itemname: itemname
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: res => {
            app.globalData.shopId = app.globalData.loginAccount
            app.globalData.shopIsMine = true
            wx.navigateTo({
              url: '../secondhand-shop/shop',
            })
            wx.showToast({
              title: '编辑成功',
            })
          }
        })
      }
    }
  },

  bindDateChange: function(e) {
    this.setData({
      date: e.detail.value
    })
    
  }


})